package cn.sumpu.app.guoguojie.biz.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.transaction.annotation.Transactional;

import cn.sumpu.app.guoguojie.biz.ContactBiz;
import cn.sumpu.app.guoguojie.biz.DetailBiz;
import cn.sumpu.app.guoguojie.dao.ContactDao;
import cn.sumpu.app.guoguojie.dao.DetailDao;
import cn.sumpu.app.guoguojie.domain.Contact;
import cn.sumpu.app.guoguojie.domain.Detail;
import cn.sumpu.app.guoguojie.exception.AppBusinessException;
import cn.sumpu.app.guoguojie.util.Common;

public class ContactBizImpl implements ContactBiz {
	private ContactDao contactDao;

	private DetailBiz detailBiz;

	private DetailDao detailDao;

	public void setContactDao(ContactDao contactDao) {
		this.contactDao = contactDao;
	}

	public void setDetailBiz(DetailBiz detailBiz) {
		this.detailBiz = detailBiz;
	}

	public void setDetailDao(DetailDao detailDao) {
		this.detailDao = detailDao;
	}

	public List<Contact> getContactListMember(String member)
			throws AppBusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("member", member);
		List<Contact> list = contactDao.getContactList(map);
		if (list != null && list.size() > 0)
			return list;
		return null;
	}

	public void updateContact(Contact contact) throws AppBusinessException {

		contactDao.updateContact(contact);
	}

	public Contact addContact(Contact contact) throws AppBusinessException {
		if(!"".equals(contact.getName())&&!"".equals(contact.getValue())){
			contactDao.insert(contact);
		}
		return contact;
	}
	
	public Contact delContact(Contact contact) throws AppBusinessException {
		contactDao.delContact((contact));
		return contact;
	}

	public void addContactList(List<Contact> list) throws AppBusinessException {
		for (int i = 0; i < list.size(); i++) {
			contactDao.insert(list.get(i));
		}
	}

	@Transactional(rollbackForClassName = { "cn.sumpu.app.guoguojie.exception.AppBusinessException" }, timeout = 10)
	@Override
	public void addDetail(Detail detail) throws AppBusinessException {
		if (detail == null)
			return;
		Detail d = detailBiz.getDetailById(detail.getMember());
		if (d == null) {
			detailDao.insertDetail(detail);
		} else {
			detailDao.updateDetail(detail);
		}
		Contact c = new Contact();
		c.setMember(detail.getMember());
		contactDao.delContact(c);
		List<Contact> cList = detail.getContactList();
		if (cList != null && cList.size() > 0) {
			for (Contact contact : cList) {
				contact.setMember(detail.getMember());
				if (!Common.empty(contact.getName())
						&& !Common.empty(contact.getValue())) {
					if(contact.getName().length()>50)
						contact.setName(contact.getName().substring(0, 49));
					if(contact.getValue().length()>500)
						contact.setValue(contact.getValue().substring(0,499));
					contactDao.insert(contact);
				}
			}
		}
	}

}
